package models

import (
	"html"
	"strings"

	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
	"jjqzplucky.site/sz-core/internal/models"
	"jjqzplucky.site/sz-core/pkg/utils/token"
)

type MisUser struct {
	models.BaseModel
	Username string `json:"username"`
	Password string `json:"password"`
	Name     string `json:"name"`
	Sex      int8   `json:"sex"`
	Tel      string `json:"tel"`
	Email    string `json:"email"`
	DeptId   int16  `json:"deptId"`
	Job      string `json:"job"`
	RefId    int64  `json:"refId"`
	Status   int8   `json:"status"`
}

func (u *MisUser) TableName() string {
	return "mis_user"
}

func (u *MisUser) BeforeCreate(tx *gorm.DB) (err error) {
	u.BaseModel.BeforeCreate(tx)
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
	if err != nil {
		return err
	}
	u.Password = string(hashedPassword)
	u.Username = html.EscapeString(strings.TrimSpace(u.Username))
	return
}

func (u *MisUser) SaveUser() (*MisUser, error) {

	result := models.DB.Create(&u)

	if result.Error != nil {
		return nil, result.Error
	}
	return u, nil
}

func VerifyPassword(password, hashedPassword string) error {
	return bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
}

func LoginCheck(username, password string) (string, error) {
	db := models.DB
	var err error
	u := MisUser{}

	err = db.Model(u).Where("username = ?", username).Take(&u).Error
	if err != nil {
		return "", err
	}
	err = VerifyPassword(password, u.Password)
	if err != nil && err == bcrypt.ErrMismatchedHashAndPassword {
		return "", err
	}

	token, err := token.GenerateToken(u.Id)
	if err != nil {
		return "", err
	}
	return token, nil
}

func GetUserByID(id uint64) (*MisUser, error) {
	var err error
	u := MisUser{}

	err = models.DB.First(&u, id).Error
	if err != nil {
		return nil, err
	}
	return &u, nil
}
